//
//  AppDelegate.m
//  HarmonizePub
//
//  Created by rzhy on 2016/10/31.
//  Copyright © 2016年 Zy. All rights reserved.
//


/**
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG!
 */


#import "XHAppDelegate.h"
#import "Config.h"
// JPshu
#import <JPUSHService.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// BaiduMap
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import "UPPaymentControl.h"
#import "SVProgressHUD.h"
#import "WXApi.h"
#import "WXApiManager.h"
#import <AlipaySDK/AlipaySDK.h>
// UMengShare
#import <UMSocialCore/UMSocialCore.h>

static NSString * const JPush_AppKey = @"3bbd4dee470c117946e3005e";
static NSString * const BM_AppKey = @"xGI3Y7GhPGgTTju2kaOTAQf8A8CFbzQ5";
static NSString * const UM_AppKey = @"58169d98734be46e2800019e";
static NSString * const WX_AppSecret = @"a78987c89d327b8e08bb1f1571c22d3e"; // 9TWPQHdeI4VbO7noKCKmaWAl89Z0yYzK
static NSString * const WX_AppKey = @"wx8559b1c345abe70b"; // wx270df6d72a8ac5b5
static NSString * const QQ_AppKey = @"1105913530";

@interface XHAppDelegate () <JPUSHRegisterDelegate, BMKGeneralDelegate>
{
    BMKMapManager *_mapManager;
}
@end

@implementation XHAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [self isDebug];
    [self getVersion];
    
    [NSThread sleepForTimeInterval:3.0];
    
    // JPush
    [self JPushWithLaunchOptions:launchOptions];
    
    // BaiduMap
    _mapManager = [[BMKMapManager alloc] init];
    BOOL ret = [_mapManager start:BM_AppKey generalDelegate:self];
    if (!ret) XHLog(@"baidu map manager start failed!");
    
    // UMSocial
    [self setUMSocial];
    
    // Token
    NSString *token = [UserDefaultsTool stringForKey:XHToken];
    if (!token || [token isEqualToString:@""]) [UserDefaultsTool setObject:@"0" forKey:XHToken];
    
    // 微信
    [WXApi registerApp:WX_AppKey];
    
    NSDictionary *remoteNotification = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotification)
        [UserDefaultsTool setInteger:1 forKey:XHMessage];
    else
        [UserDefaultsTool setInteger:0 forKey:XHMessage];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [self getUnreadMsgCount];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - UMengShare
- (void)setUMSocial {
    // UMeng
    [[UMSocialManager defaultManager] openLog:NO];
    [[UMSocialManager defaultManager] setUmSocialAppkey:UM_AppKey];
    // 设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WX_AppKey appSecret:WX_AppSecret redirectURL:@"http://mobile.umeng.com/social"];
    // 设置分享到QQ互联的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQ_AppKey  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
}

#pragma mark - BMKGeneralDelegate
- (void)onGetNetworkState:(int)iError {
    if (0 == iError) {
//        XHLog(@"联网成功")
    } else {
        XHLog(@"onGetNetworkState %d",iError);
    }
}

- (void)onGetPermissionState:(int)iError {
    if (0 == iError) {
//        XHLog(@"授权成功")
    } else {
        XHLog(@"onGetPermissionState %d",iError);
    }
}

#pragma mark - deviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//    XHLog(@"----- deviceToken: %@ -----", deviceToken)
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark - notification
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [self getUnreadMsgCount];
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//    XHLog(@"%@", userInfo)
    [self getUnreadMsgCount];
    [JPUSHService handleRemoteNotification:userInfo];
    
    if (application.applicationState == UIApplicationStateInactive)
        [[NSNotificationCenter defaultCenter] postNotificationName:XHMessage object:nil];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - 未读消息数
- (void)getUnreadMsgCount {
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    [HTTPSTool POSTRequestHidenHUDWithPath:XHGetUnreadMsgCount cookie:cookie params:nil progress:nil success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"JSON: %@", JSON)
        [UserDefaultsTool setObject:JSON[@"data"][@"count"] forKey:XHNewMessage];
        [[NSNotificationCenter defaultCenter] postNotificationName:XHNewMessage object:nil userInfo:nil];
    } failure:nil];
}

#pragma mark - JPush
static NSString * const XHJPushMASTER_SECRET = @"1c32bd215c9563a0b9e6262a";
- (void)JPushWithLaunchOptions:(NSDictionary *)launchOptions {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    } else {
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }
    // 启动
    [JPUSHService setupWithOption:launchOptions appKey:JPush_AppKey channel:@"App Store" apsForProduction:isRelease];
    // 关闭日志
    [JPUSHService setLogOFF];
    [JPUSHService registrationID];
    // Crash日志收集
//    [JPUSHService crashLogON];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content;   // 收到推送的消息内容
    NSNumber *badge            = content.badge; // 推送消息的角标
    NSString *body             = content.body;  // 推送消息体
    UNNotificationSound *sound = content.sound; // 推送消息的声音
    NSString *subtitle         = content.subtitle; // 推送消息的副标题
    NSString *title            = content.title; // 推送消息的标题
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
//        XHLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
    } else {
        // 判断为本地通知
        XHLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}", body, title, subtitle, badge, sound, userInfo);
    }
    [self getUnreadMsgCount];
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    NSDictionary * userInfo        = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSNumber *badge            = content.badge; // 推送消息的角标
    NSString *body             = content.body;  // 推送消息体
    UNNotificationSound *sound = content.sound; // 推送消息的声音
    NSString *subtitle         = content.subtitle; // 推送消息的副标题
    NSString *title            = content.title; // 推送消息的标题
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
//        XHLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
    } else {
        // 判断为本地通知
        XHLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive)
    [[NSNotificationCenter defaultCenter] postNotificationName:XHMessage object:nil];
    
    completionHandler(); // 系统要求执行这个方法
}
#endif

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 = [[dic description] stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];;
    
    return str;
}

#pragma mark - 支付回调
// ios 9以前使用的方法
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    // 支付回调
    [self callBackWithUrl: url];
    
    return [[UMSocialManager defaultManager] handleOpenURL:url];
}

// ios 9以前使用的方法
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    // 支付回调
    [self callBackWithUrl: url];
    
    return [[UMSocialManager defaultManager] handleOpenURL:url];
}

// IOS 9.0 以后的方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    [self callBackWithUrl: url];
    return [[UMSocialManager defaultManager] handleOpenURL:url];
}

// 支付回调
- (void)callBackWithUrl: (NSURL *)url {
    // 支付宝回调
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult: url standbyCallback:^(NSDictionary *resultDic) {
//            XHLog(@"result = %@", resultDic);
            NSString *result = resultDic[@"result"];
            if (result.length) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Alipay_PaySuccess" object:nil userInfo:resultDic];
            }
        }];
        
    }
    // 银联回调
    else if([url.host isEqualToString:@"uppayresult"]){
        // 银联支付回调
        [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
            //结果code为成功时，先校验签名，校验成功后做后续处理
            if([code isEqualToString:@"success"]) {
                //判断签名数据是否存在,如果没有签名数据，建议商户app后台查询交易结果
                if(data == nil){
                    return;
                }
                // 与后台查询验证是否支付成功
                NSString *orderId = [UserDefaultsTool objectForKey:XHUnionPayOrderId];
                
                [self verify: orderId];
            }
            else if([code isEqualToString:@"fail"]) {
                //交易失败
                XHLog(@"支付失败");
            }
            else if([code isEqualToString:@"cancel"]) {
                //交易取消
                XHLog(@"支付取消");
            }
        }];
    }
    // 微信支付回调
    else if ([url.host isEqualToString:@"pay"]){
        [WXApi handleOpenURL:url delegate: [WXApiManager sharedManager]];
    }
}

// 与后台查询验证支付结果
- (void)verify: (NSString *)resultStr
{
    NSDictionary *params = @{@"orderId" : resultStr,
                             @"type" : @(1)}; // 1 银联  2 微信  3 支付
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    [HTTPSTool POST:XHQueryUnionPay params:params cookie:cookie success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"验证成功JSON: %@", JSON);
        NSString *result = [NSString stringWithFormat:@"%@", [JSON valueForKey:@"msg"]];
        if ([result isEqualToString:@"充值成功"]) {
            [SVProgressHUD showSuccessWithStatus: [JSON valueForKey:@"msg"]];
        } else if ([result isEqualToString:@"处理中"]){
            [SVProgressHUD showErrorWithStatus: [JSON valueForKey:@"msg"]];
        } else if ([result isEqualToString:@"扣款失败"]){
            [SVProgressHUD showErrorWithStatus: [JSON valueForKey:@"msg"]];
        } else if ([result isEqualToString:@"处理失败"]){
            [SVProgressHUD showErrorWithStatus: [JSON valueForKey:@"msg"]];
        }
    } failure:^(NSError * _Nullable error) {
        XHLog(@"发送验证请求失败");
    }];
}


#pragma mark - 检查更新
- (void)getVersion {
    NSString *path = @"https://itunes.apple.com/lookup";
    NSDictionary *param = @{@"id" : @"1412631534"};
    __weak typeof(self) weakSelf = self;
    [HTTPSTool POST:path params:param cookie:nil success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"JSON: %@", JSON);
        NSArray *array = JSON[@"results"];
        if (array.count) {
            NSDictionary *dict = array.lastObject;
            [weakSelf updatedVersion:dict];
        }
    } failure:nil];
}

- (void)updatedVersion:(NSDictionary *)dict {
    NSString *version = dict[@"version"];
    NSString *key = @"CFBundleShortVersionString";
    NSString *sysVersion = [NSBundle mainBundle].infoDictionary[key];
    NSInteger ver = [[version stringRemoveSpecialSymbol:@"."] integerValue];
    NSInteger sysVer = [[sysVersion stringRemoveSpecialSymbol:@"."] integerValue];
    if (sysVer < ver) {
        [UserDefaultsTool setBool:YES forKey:XHIsUpdateVersion];
        // 有新版本
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您有新版本可以更新!" message:@"是否马上更新新版本?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:XHAppUrl];
            if ([[UIApplication sharedApplication] canOpenURL:url])
                [[UIApplication sharedApplication] openURL:url];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:sureAction];
        [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    } else {
        [UserDefaultsTool setBool:NO forKey:XHIsUpdateVersion];
    }
}

#pragma mark - Debug
- (void)isDebug {
    NSString *key = @"CFBundleShortVersionString";
    NSString *saveVersion = [UserDefaultsTool stringForKey:key];
    BOOL b = [UserDefaultsTool boolForKey:XHIsDebug];
    if (saveVersion == nil || b) {
        [self getDebug];
    }
}

- (void)getDebug {
    NSDictionary *param = @{@"deviceType" : @"ios", @"appType" : @"pub"};
    [HTTPSTool POST:XHgetVersion params:param cookie:nil success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"JSON: %@", JSON);
        NSInteger integer = [JSON[@"isDebug"] integerValue];
        BOOL isDebug = integer;
        [UserDefaultsTool setBool:isDebug forKey:XHIsDebug];
    } failure:^(NSError * _Nonnull error) {
        [UserDefaultsTool setBool:YES forKey:XHIsDebug];
    }];
}

@end
